<?php
namespace ImiApp\Module\IM\HttpController;

use Imi\ConnectContext;
use Imi\RequestContext;
use Imi\Controller\HttpController;
use Imi\Server\View\Annotation\View;
use Imi\Server\Route\Annotation\Route;
use Imi\Server\Route\Annotation\Action;
use Imi\Server\Route\Annotation\Controller;
use ImiApp\Module\Member\Annotation\LoginRequired;
use Imi\Server\Route\Annotation\WebSocket\WSConfig;

/**
 * 测试
 * @Controller
 * @View(renderType="html")
 */
class HandShakeController extends HttpController
{
    /**
     * @Action
     * @LoginRequired
     * 
     * @Route("/im")
     * @WSConfig(parserClass=\Imi\Server\DataParser\JsonArrayParser::class)
     * @return void
     */
    public function im()
    {
        // 握手处理，什么都不做，框架会帮你做好
        /** @var \ImiApp\Module\Member\Service\MemberSessionService $memberSession */
        $memberSession = RequestContext::getBean('MemberSessionService');
        $memberId = $memberSession->getMemberId();

        $currentFd = $this->request->getSwooleRequest()->fd;
        var_dump('currentFd',$currentFd);
        if(!$memberId){
            var_dump('没有登录！');
            $this->request->getServerInstance()->getSwooleServer()->close($currentFd);
        }


        ConnectContext::set('memberId', $memberId);
        $flag = 'user_id-' . $memberId;

        var_dump('im/握手',$flag,'currentFd'.$currentFd);
        
        if(!ConnectContext::bindNx($flag, $currentFd))//绑定连接，如果已绑定返回false
        {
            $fd = ConnectContext::getFdByFlag($flag);//使用标记（UID）获取连接编号
            if($fd)
            {
                // $this->request->getServerInstance()->getSwooleServer()->close($fd);
            }
            if(!ConnectContext::bindNx($flag, $currentFd))
            {
                // $this->request->getServerInstance()->getSwooleServer()->close($currentFd);
            }
        }
    }

}